#include "mainwindow.h"
#include "ui_mainwindow.h"

/**
 * @brief  设置浮动窗口类对象指针全局化
 */
ads::CDockManager* m_pDockManager;

/**
 * @brief  项目主窗口类构造函数
 * @param  parent 父窗口
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    // 定义浮动窗口设计类
    m_pDockManager = new ads::CDockManager(this);
    m_pDockManager->setAttribute(Qt::WA_DeleteOnClose);

    // 加载数据库配置文件
    MyDatabase_P = new MyDatabase_Parameters(this);
    m_configPath = "AGV.ini";
    openDatabase(m_configPath);

    // 外部窗口类
    Add_newAGV = new AddNewAGV(this);
    AGV_Send_Task = new AGV_Send_TaskDialog(this);
    AGV_Send_API = new AGV_Send_API_Commands(this);
    TableButton = new TableButtonFunction(this);
    connect(&MyDatabase::getInstance(), &MyDatabase::setButton, TableButton, &TableButtonFunction::addButton);

    // 初始化日志系统
    Logger::getInstance()->init("logs", LogLevel::DEBUG, true);
    Logger::getInstance()->setMaxFileSize(1024 * 1024); // 1MB
    Logger::getInstance()->setMaxBackupCount(5);
    logDialog = new LoggerDialog(this);
    // 使用日志
    LOG_INFO("Application started 开始");

    // 测试
    Singals = new SignalAnalysis(this);

    // 浮动窗口声明与添加
    AGV_D = new AGV_Display(this);
    DockWidget_D = new ads::CDockWidget("列表参数窗口", this);
    DockWidget_D->setWidget(AGV_D);
    AGV_D->setAttribute(Qt::WA_DeleteOnClose);

    AGV_F_S = new AGV_Function_Selection(this);
    DockWidget_F_S = new ads::CDockWidget("功能选择窗口", this);
    DockWidget_F_S->setWidget(AGV_F_S);
    AGV_F_S->setAttribute(Qt::WA_DeleteOnClose);

    // 设置中心窗口
    m_pDockManager->setCentralWidget(DockWidget_D);
    DockWidget_D->setFeature(ads::CDockWidget::DockWidgetMovable, true);
    DockWidget_D->setFeature(ads::CDockWidget::NoTab, true);
    // 添加浮动窗口
    m_pDockManager->addDockWidget(ads::RightDockWidgetArea, DockWidget_D);
    m_pDockManager->addDockWidget(ads::LeftDockWidgetArea, DockWidget_F_S);

    // 初始化连接
    connectInit();
}

/**
 * @brief  项目主窗口类析构函数
 */
MainWindow::~MainWindow()
{
    delete ui;
}

/**
 * @brief  存放各种连接的函数
 */
void MainWindow::connectInit()
{
    // 连接显示选项
    connect(AGV_F_S, &AGV_Function_Selection::send_window_number, AGV_D, &AGV_Display::display_specified_window);
    connect(AGV_F_S, &AGV_Function_Selection::sendnewAGV, this, &MainWindow::showAdd_newAGV);
    // 显示下发任务界面
    connect(AGV_F_S, &AGV_Function_Selection::sendAGV_task, this, &MainWindow::showAGV_Send_TaskDialog);

    connect(Add_newAGV, &AddNewAGV::senddatalist, this ,&MainWindow::getnewAGVdata);
    connect(this, &MainWindow::sendnewAGVlist, AGV_D, &AGV_Display::addvehicle);
    connect(this, &MainWindow::sendTaskDialogIndex, AGV_Send_Task, &AGV_Send_TaskDialog::showDialog);

    connect(AGV_D, &AGV_Display::sendnewAGV, TableButton, &TableButtonFunction::alterAddData);
    connect(AGV_D, &AGV_Display::sendtablename, TableButton, &TableButtonFunction::AddViewWindow);
    connect(TableButton, &TableButtonFunction::sendtoAPIdisplay, AGV_Send_API, &AGV_Send_API_Commands::showDisplay_View);
    // 显示接替任务界面
    connect(TableButton, &TableButtonFunction::sendAGV_task, this, &MainWindow::showAGV_Send_TaskDialog);
    connect(AGV_D, &AGV_Display::sendtoAPIdisplay, AGV_Send_API, &AGV_Send_API_Commands::showDisplay_View);

    // 数据库错误修改
    connect(Add_newAGV, &AddNewAGV::sendDBerror, this, &MainWindow::AlterMyDatabase);
    connect(AGV_D, &AGV_Display::sendDBerror, this, &MainWindow::AlterMyDatabase);
    connect(AGV_Send_Task, &AGV_Send_TaskDialog::sendDBerror, this, &MainWindow::AlterMyDatabase);
    connect(AGV_Send_API, &AGV_Send_API_Commands::sendDBerror, this, &MainWindow::AlterMyDatabase);
    // 主窗口数据库操作
    connect(ui->action_database, &QAction::triggered, this, &MainWindow::AlterMyDatabase);
    connect(ui->action_reconnect, &QAction::triggered, this, &MainWindow::reconnectDtabase);
    connect(ui->action_opendatabase, &QAction::triggered, this, &MainWindow::AlterMyDatabase);

    // 窗口显示
    connect(ui->action_UI_choose, &QAction::triggered, this, &MainWindow::showUI);
    connect(ui->action_parameters, &QAction::triggered, this, &MainWindow::showDisplyWindow);

    // 测试
    connect(ui->action_test, &QAction::triggered, this, &MainWindow::test);

    // 监听中间层通信信号传入测试
    connect(this, &MainWindow::sendobj, Singals, &SignalAnalysis::handleSignal);

    // 日志
    connect(ui->action_log, &QAction::triggered, this, &MainWindow::showLogDialog);

    // 调色盘
    connect(ui->action_color, &QAction::triggered, this, &MainWindow::showColorDialog);

}

/**
 * @brief  判断配置文件打开情况以及数据库连接情况
 * @param  configPath 数据库配置文件名
 * @return  返回数据库是否连接成功
 */
bool MainWindow::openDatabase(const QString& configPath)
{
    int result = loadConfig(configPath);
    if(result==-1)
    {
        LOG_ERROR("数据库配置文件打开失败!");
        //QMessageBox::warning(nullptr, "警告", "数据库配置文件打开失败!");
        QMessageBox::critical(nullptr, "警告", "数据库配置文件打开失败", QMessageBox::Ok);
        return false;
    }else {
        if(result==0)
        {
            LOG_ERROR("数据库打开失败,数据库参数配置错误!");
            //QMessageBox::warning(nullptr, "警告", "数据库打开失败,参数配置错误,修改数据库配置参数后重新连接");
            QMessageBox::critical(nullptr, "警告", "数据库打开失败,参数配置错误,修改数据库配置参数后重新连接", QMessageBox::Ok);
            return false;
        }else{
            return true;
        }
    }
}

/**
 * @brief  获取数据库配置文件数据
 * @param  configPath 数据库配置文件名
 * @return  返回不同结果
 */
int MainWindow::loadConfig(const QString& configPath)
{
    QString fullPath = configPath;
    if (!QDir::isAbsolutePath(configPath)) {
        fullPath = QCoreApplication::applicationDirPath() + "/" + configPath;
    }
    QFileInfo info(fullPath);
    if(!info.exists())
    {
        return -1;
    }
    QSettings settings(fullPath, QSettings::IniFormat);
    settings.beginGroup("Database");
    QMap<QString, QVariant> infomap;
    infomap["ip"] = settings.value("Host").toString();
    infomap["port"] = settings.value("Port").toInt();
    infomap["db"] = settings.value("Dbname").toString();
    infomap["username"] = settings.value("User").toString();
    infomap["password"] = settings.value("Password").toString();
    settings.endGroup();
    if(MyDatabase::getInstance().openDatabase())
    {
        if(MyDatabase::getInstance().AlterDatabase(infomap))
        {
            return 0;
        }
    }
    return 1;
}

/**
 * @brief  保存数据库配置文件数据
 * @param  configPath 数据库配置文件名
 * @return  返回保存是否成功
 */
bool MainWindow::saveConfig(const QString& configPath, QMap<QString, QVariant>& data)
{
    if(data.isEmpty())
    {
        return false;
    }
    QString fullPath = configPath;
    if (!QDir::isAbsolutePath(configPath)) {
        fullPath = QCoreApplication::applicationDirPath() + "/" + configPath;
    }
    QFileInfo info(fullPath);
    if(!info.exists())
    {
        return false;
    }
    QSettings settings(fullPath, QSettings::IniFormat);
    settings.beginGroup("Database");
    settings.setValue("Host", data["ip"].toString());
    settings.setValue("Port", data["port"].toInt());
    settings.setValue("Dbname", data["db"].toString());
    settings.setValue("User", data["username"].toString());
    settings.setValue("Password", data["password"].toString());
    settings.sync(); // 立即写入磁盘
    if (settings.status() == QSettings::NoError) {
        LOG_INFO("数据库配置更新成功");
    } else {
        LOG_ERROR("数据库配置更新失败");
    }

    settings.endGroup();
    return true;
}

/**
 * @brief  重新连接数据库
 */
void MainWindow::reconnectDtabase()
{
    if(openDatabase(m_configPath))
    {
        LOG_INFO("数据库重新连接成功!");
        QMessageBox::information(nullptr,
                                 "成功",
                                 "数据库重新连接成功!");
    }
}

/**
 * @brief  修改数据库配置参数
 */
void MainWindow::AlterMyDatabase()
{
    MyDatabase_P->setWindowTitle("数据库参数");
    QString fullPath = m_configPath;
    if (!QDir::isAbsolutePath(m_configPath)) {
        fullPath = QCoreApplication::applicationDirPath() + "/" + m_configPath;
    }
    QFileInfo info(fullPath);
    if(!info.exists())
    {
        return;
    }
    QSettings settings(fullPath, QSettings::IniFormat);
    settings.beginGroup("Database");
    QMap<QString, QVariant> infomap;
    infomap["ip"] = settings.value("Host").toString();
    infomap["port"] = settings.value("Port").toInt();
    infomap["db"] = settings.value("Dbname").toString();
    infomap["username"] = settings.value("User").toString();
    infomap["password"] = settings.value("Password").toString();
    settings.endGroup();
    MyDatabase_P->setData(infomap);
    MyDatabase_P->exec();
    QMap<QString, QVariant> data = MyDatabase_P->saveData();
    saveConfig(m_configPath, data);
}

/**
 * @brief  显示界面索引选择界面
 */
void MainWindow::showUI()
{
    m_pDockManager->addDockWidget(ads::LeftDockWidgetArea, DockWidget_F_S);
}

/**
 * @brief  显示表数据显示界面
 */
void MainWindow::showDisplyWindow()
{
    m_pDockManager->addDockWidget(ads::RightDockWidgetArea, DockWidget_D);
}

/**
 * @brief  小车添加界面
 */
void MainWindow::showAdd_newAGV()
{
    Add_newAGV->InitData();
    Add_newAGV->exec();
}

/**
 * @brief  小车添加数据
 * @param  list 添加的小车信息
 */
void MainWindow::getnewAGVdata(const QStringList &list)
{
    emit sendnewAGVlist(list);
}

/**
 * @brief  任务发送界面
 * @param  index 显示指定界面的索引
 */
void MainWindow::showAGV_Send_TaskDialog(const int& index, const int& taskId)
{
    sendTaskDialogIndex(index,taskId);
    AGV_Send_Task->exec();
}

/**
 * @brief  日志界面显示
 */
void MainWindow::showLogDialog()
{
    logDialog->exec();
}

/**
 * @brief  显示调试盘
 */
void MainWindow::showColorDialog() {
    // 显示系统调色盘并获取颜色
    QColor color = QColorDialog::getColor(Qt::white, this, "选择颜色",
        QColorDialog::ShowAlphaChannel | QColorDialog::DontUseNativeDialog);

    if (color.isValid()) {
        // 更新预览区域颜色（两种方式）
        colorWidget->setStyleSheet(QString("background-color: %1;").arg(color.name()));

        // 备选方案：使用QPalette设置
        QPalette palette = colorWidget->palette();
        palette.setColor(QPalette::Window, color);
        colorWidget->setPalette(palette);
        colorWidget->setAutoFillBackground(true);
    }
}

void MainWindow::test()
{
    // 创建主对象
    QJsonObject person;
    person.insert("function_code", 602);
    person.insert("request_id", "4f964b3e-63db-4c7a-ab22-c5cd0244567b");

    // 添加嵌套对象
    QJsonObject jobInfo;
    jobInfo.insert("code", 99);
    jobInfo.insert("info", "成功");
    person.insert("data_info", jobInfo);


    emit sendobj(person);
}




